<?php

namespace App\Http\Middleware\OpenShop;

use App\Exceptions\Custom\ResponseHttpException;
use App\Models\Common\ConfigModel;
use App\Models\OpenShop\Common\OpenShopOrderManagerModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopOrganizationManageModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopOrganizationManageUserModel;
use App\Service\OpenShop\Feishu\ConfigService;
use App\Service\OpenShop\SiteLocation\AuthService;
use App\Service\OpenShop\User\RmsUserService;
use Closure;
use Exception;
use GuzzleHttp\Client;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Overtrue\Pinyin\Pinyin;

class WangGuiCityByPower
{

    /**
     * 中间件判断是否有城市选择，并根据权限去筛选
     * @param Request $request
     * @param Closure $next
     * @return mixed
     */
    public function handle(Request $request, Closure $next, string $type = 'applet')
    {
        //城市参数
        $city = $request->get('city', '');

        // 不同平台传的参数
        $headerPlatformName = $request->header('platformName','');

        if ($type == 'applet') {
            $userId = AuthService::getRmsUserInfo($request)['userId'];
        } else {
            $userId = getRmsUserInfoByAuth()->id;
        }


        //获得省总用户ID
        $organizationManage = OpenShopOrganizationManageModel::query()
            ->where('type', 1)
            ->first();
        if (null == $organizationManage) {
            throw new ResponseHttpException(404, null, '组织管理总部不存在');
        }
        //总部人员
        $operationAttacheUser = collect(json_decode($organizationManage->operationAttacheUser, true))->pluck('uid')->toArray();

        //总部权限
        $isAllPower      = false;
        $provinces       = [];
        $businessUserIds = OpenShopOrganizationManageUserModel::query()->where('type', OpenShopOrganizationManageUserModel::TYPE_SOLICIT_BUSINESS)->pluck('userId')->toArray();
        if (in_array($userId, array_merge($operationAttacheUser, [$organizationManage->operationUid], $businessUserIds))) {
            $isAllPower = true;
        } else {
            //判断用户是否为省总
            $provinceManagerIds = OpenShopOrganizationManageModel::query()
                ->pluck('operationUid')->toArray();

            //白名单
            $whiteListJson = ConfigModel::query()
                ->where('module', 'wanggui')
                ->where('name', 'regionalWhiteList')
                ->value('value');
            $whiteListArr  = json_decode($whiteListJson, true);

            //判断是否是省区开发
            $manageUser = OpenShopOrganizationManageUserModel::query()
                ->where('userId', $userId)
                ->whereIn('type', [OpenShopOrganizationManageUserModel::TYPE_PROVINCE_DEVELOP, OpenShopOrganizationManageUserModel::TYPE_INCREASE_MANAGER, OpenShopOrganizationManageUserModel::TYPE_SITE_SELECTION_DEVELOPMENT])
                ->get();

            if (!$manageUser->count() && !in_array($userId, array_column($whiteListArr, 'userId')) && !in_array($userId, $provinceManagerIds) && $headerPlatformName != 'operate') {
                throw new ResponseHttpException(403, null, '您没有省区开发权限');
            }
            $selfProvinceCode = [];
            foreach ($whiteListArr as $power) {
                if ($power['userId'] == $userId) {
                    foreach ($power['provinceCodeArr'] as $provinceCode) {
                        $selfProvinceCode[] = $provinceCode;
                    }
                }
            }

            //获得省区列表
            $manageModel = OpenShopOrganizationManageModel::query()
                ->whereIn('id', $manageUser->pluck('manageId')->toArray())
                ->orWhere('operationUid', $userId)
                ->with(['regionRel'])
                ->get();

            if ($manageModel == null && !count($selfProvinceCode) && $headerPlatformName != 'operate') {
                throw new ResponseHttpException(400, null, '未配置省区列表');
            }
            optional($manageModel)->each(function (OpenShopOrganizationManageModel $openShopOrganizationManageModel) use (&$provinces) {
                $provinces = array_merge($provinces, (optional($openShopOrganizationManageModel->regionRel)->pluck('provinceCode')->toArray() ?: []));
            });
            $provinces = array_unique(array_merge($provinces, $selfProvinceCode));
        }
        //获得对应省区列表
        $provinceList = self::getChinaDistrict();
        $cityList     = [];
        $adcode       = [];
        foreach ($provinceList as $province) {
            if (in_array($province['name'], ['澳门特别行政区', '香港特别行政区', '台湾省'])) {
                continue;
            }
            if ($isAllPower || in_array($province['adcode'], $provinces)) {
                foreach ($province['districts'] as $city) {
                    $cityList[] = $city['name'];
                    $adcode[]   = $city['adcode'];
                }
            }
        }
        if (!count($cityList) && $headerPlatformName != 'operate') {
            throw new ResponseHttpException(400, null, '您暂无区域列表');
        }
        $request->haveCity   = $cityList;
        $request->haveAdcode = $adcode;
        $request->userId     = $userId;
        return $next($request);
    }

    /**
     * 获取热门城市
     * @return array
     * @throws Exception
     */
    public static function hotList(): array
    {
        return ConfigService::config('wanggui', 'hotCity');
    }

    /**
     * 获得行政区域
     * @return array
     */
    public static function getChinaDistrict(): array
    {
        return Cache::remember('openShop:wanggui:districts:cache:all', 864000, function () {
            $amapKey  = self::getRandomAmapKey();
            $url      = "https://restapi.amap.com/v3/config/district?keywords=中国&subdistrict=3&key={$amapKey}";
            $response = (new Client(['http_errors' => false]))
                ->get($url);
            $body     = $response->getBody()->getContents();
            //获取所有省份
            return json_decode($body, true)['districts'][0]['districts'];
        });
    }


    /**
     * 提供的key
     * @return mixed
     */
    public static function getRandomAmapKey()
    {
        //$keys = [
        //    '49ac92f420af133e6bf6ce5586219c2a',   //彼得潘
        //    'fbe7159dbb34e2a0dbdd687cb7db7933',   //五郎
        //    '638a5878af3080db5d6265cd644f170a',   //飞雨
        //    'dcdd5a123832dc8c534c6d2a3285bd67',   //希曼
        //    '5338a2a7cde8987621846caf53f0b1c1',   //太狼
        //    'ffa97277887e1cf2b2fc0944cd86ec7d',   //公司
        //];

        $configValue = Cache::remember('amap:web_serve_api_key', 3600, function () {
            return (string)ConfigModel::query()
                ->where('module', 'amap')
                ->where('name', 'webServeApiKey')
                ->value('value');
        });

        if ('' === $configValue) {
            $keys = ['cce383493bc3b56e8488a6c3c275ba85'];  // 夏目的key兜底
            Cache::forget('amap:web_serve_api_key');
        } else {
            $configArr = json_decode($configValue, true);
            $keys      = collect($configArr['normal'])->pluck('key')->toArray();
        }

        return collect($keys)->random(1)[0];
    }

}
